package com.ruoyi.business.Schedul;

import com.ruoyi.user.domain.ServiceEvaluate;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.metrics.ParsedAvg;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author ffc
 * @version 1.0
 * @description: TODO
 * @className: Rate
 * @date 2024/9/19 20:32
 */
@Component
public class Rate {

    @Autowired
    private ElasticsearchRestTemplate restTemplate;

    @Autowired
    private RedisTemplate redisTemplate;

    @Scheduled(cron = "*/10 * * * * ?")
    public void updateRate() {
        NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();
        queryBuilder.addAggregation(AggregationBuilders.terms("shopAggs")
                .field("mid")
                .subAggregation(AggregationBuilders.avg("rateAvgAggs")
                        .field("rate")));
        SearchHits<ServiceEvaluate> searchHits = restTemplate.search(queryBuilder.build(),
                ServiceEvaluate.class, IndexCoordinates.of("service_evaluate"));
        Aggregations aggregations = (Aggregations) searchHits.getAggregations().aggregations();
        ParsedLongTerms brandAggs = (ParsedLongTerms) aggregations.get("shopAggs");
        for (Terms.Bucket bucket : brandAggs.getBuckets()) {
            String key = bucket.getKey().toString();
            System.out.println(key);
            ParsedAvg rateAvgAggs = (ParsedAvg) bucket.getAggregations().get("rateAvgAggs");
            long rate = Math.round(rateAvgAggs.getValue());
            redisTemplate.opsForValue().set("rate:" + key, rate);
        }
    }
}
